package fr.poy.mygluco.server;

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.logging.Level;
import java.util.logging.Logger;
 
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.FileUploadBase.SizeLimitExceededException;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.IOUtils;
import org.mortbay.jetty.Request;

/**
 *  
 *
 * - upload file
 * - stockage en mémoire dans la session 
 */
@SuppressWarnings("serial")
public class UploadServlet extends HttpServlet{

	private static Logger log = Logger.getLogger(UploadServlet.class.getName());
	private static long maxSize = 500000;
	public static String FILE_KEY = "_File.Upload_";

	public void doPost(HttpServletRequest req, HttpServletResponse res)	throws ServletException, IOException {
		log.finest("Upload");
		try {
			ServletFileUpload upload = new ServletFileUpload();
			upload.setSizeMax(maxSize);
			res.setContentType("text/plain");
			 
			try {
				FileItemIterator iterator = upload.getItemIterator(req);
				while (iterator.hasNext()) {
					FileItemStream item = iterator.next();
					InputStream in = item.openStream();

					if (!item.isFormField()) {//File
						String fieldName = item.getFieldName();
						String fileName = item.getName();
						String contentType = item.getContentType();

						log.finest("-----      UPLOAD     ---------");
						log.finest("fileName = " + fileName);
						log.finest("field name = " + fieldName);
						log.finest("contentType = " + contentType);

						String fileContents = null;
						try {
							fileContents = IOUtils.toString(in);
							log.finest("lenght: " + fileContents.length());
							//
							req.getSession().setAttribute(FILE_KEY, fileContents);
						} finally {
							IOUtils.closeQuietly(in);
						} 
					}
				}
			} catch (SizeLimitExceededException e) {
				//TODO limit upload
				log.log(Level.SEVERE, "TODO Upload limit "+ e.getPermittedSize() + "  - file " + e.getActualSize());
			}
		} catch (Exception ex) {
			log.log(Level.SEVERE, "Upload", ex);
			throw new ServletException(ex);
		}
	}
}
